//
//  ViewController.m
//  视屏录制
//
//  Created by 王位 on 9/1/16.
//  Copyright © 2016 王位. All rights reserved.
//

#import "BSImageViewController.h"

#import <AVFoundation/AVFoundation.h>

#import "CALayer+ZUtility.h"

#import "UIView+HM.h"

#import "BSAddFairViewController.h"

@interface BSImageViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate>

@property(nonatomic,strong)AVCaptureSession * session;

@property(nonatomic,strong)UIImage * image;

@property(nonatomic,strong)AVCaptureVideoDataOutput * output;

@property(nonatomic,strong)UIImageView * imageView;

@end



@implementation BSImageViewController

#define Width self.view.bounds.size.width

#define Height self.view.bounds.size.height
-(void)viewDidLoad
{
    self.session = [[AVCaptureSession alloc]init];
    
    
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    
    NSError * error;
    
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    if([self.session canAddInput:input])
    {
        [self.session addInput:input];
    }
    
    AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc]init];
    
    
    
    if([self.session canAddOutput:output])
    {
        [self.session addOutput:output];
    }
    
    [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
    
    
    output.videoSettings =
    [NSDictionary dictionaryWithObject:
     [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
    
    [self.session startRunning];
    
    AVCaptureVideoPreviewLayer * layer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    
    layer.frame = self.view.bounds;
    
    [self.view.layer addSublayer:layer];
    
    //设置有效界面
    


    
    [self addHeadView];
    
    [self addBottom];
    
     self.output = output;
    
}

//添加底部的View
-(void)addBottom
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,self.view.bounds.size.height - 300 , self.view.bounds.size.width, 300)];
    
    view.backgroundColor =[UIColor whiteColor];
    
    [self.view addSubview:view];
    
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
    
    btn.x = (view.w - btn.w) * 0.5;
    
    btn.y = (view.h - btn.h) * 0.5;
    
    btn.layer.cornerRadius = btn.w / 2;
    
    btn.layer.masksToBounds = YES;
    
    [btn setImage:[UIImage imageNamed:@"IMG_0676"] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(stopTakePicture) forControlEvents:UIControlEventTouchDown];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    
    
    
    [view addSubview:btn];
    
    
    [view addSubview:self.imageView];
    
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, M_PI_2);
    
}

//点击拍照按钮 调用
-(void)stopTakePicture
{
    NSLog(@"%@",self.image);
    
    //获取图片
    
    //跳转到下个控制器
    
    BSAddFairViewController  * fairViewC =[[BSAddFairViewController alloc]init];
    
    fairViewC.pictureImage = self.image;
    
    [self presentViewController:fairViewC animated:YES completion:^{
        
    }];
}


//添加照相机头上按钮
-(void)addHeadView
{

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0,Width ,44)];
    
    view.backgroundColor = [UIColor whiteColor];
    
    UIButton * cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0,  view.frame.size.height, view.frame.size.height)];
    
    
    
    [cancelBtn setImage:[UIImage imageNamed:@"IMG_0672"] forState:UIControlStateNormal];
    

    
    UIButton * againBtn = [[UIButton alloc]initWithFrame:CGRectMake( view.frame.size.width - 2*view.frame.size.height, 0,  view.frame.size.height, view.frame.size.height)];
    
    [againBtn setImage:[UIImage imageNamed:@"IMG_0673"] forState:UIControlStateNormal];
    
    UIButton * flashlightBtn = [[UIButton alloc]initWithFrame:CGRectMake( view.frame.size.width - view.frame.size.height, 0,  view.frame.size.height, view.frame.size.height)];
    
    [flashlightBtn setImage:[UIImage imageNamed:@"IMG_0674"] forState:UIControlStateNormal];
    
    [view addSubview:cancelBtn];
    
    [view addSubview:againBtn];
    
    [view addSubview:flashlightBtn];
    
    [self.view addSubview:view];
    
    [cancelBtn addTarget:self action:@selector(didClicCancelBtn) forControlEvents:UIControlEventTouchDown];
    
}

//取消按钮  回到上一个界面
-(void)didClicCancelBtn
{
    [self.session stopRunning];
    
   
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}


-(BOOL)prefersStatusBarHidden
{
    return YES;
}



- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
    
    UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
    
    
    self.image = image;
    
    
}
// 通过抽样缓存数据创建一个UIImage对象
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    // 为媒体数据设置一个CMSampleBuffer的Core Video图像缓存对象
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // 锁定pixel buffer的基地址
    CVPixelBufferLockBaseAddress(imageBuffer, 0);
    
    // 得到pixel buffer的基地址
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    
    // 得到pixel buffer的行字节数
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // 得到pixel buffer的宽和高
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    // 创建一个依赖于设备的RGB颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // 用抽样缓存的数据创建一个位图格式的图形上下文（graphics context）对象
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    // 根据这个位图context中的像素数据创建一个Quartz image对象
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    // 解锁pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    
    // 释放context和颜色空间
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    // 用Quartz image创建一个UIImage对象image
    UIImage *image = [UIImage imageWithCGImage:quartzImage];
    
    // 释放Quartz image对象
    CGImageRelease(quartzImage);
    
    return (image);
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
